import json
import re

from django.contrib.auth import login, authenticate, logout
from django.http import JsonResponse
# Create your views here.
from django.views import View
from django_redis import get_redis_connection

from apps.users.models import User, Address
from apps.users.utils import generate_verify_token, chack_verify_token
from celery_tasks.email.tasks import send_verify_mail
from utils.viewmixin import LoginMixin


class UsernameCountView(View):
    def get(self, request, username):
        print(username)

        count = User.objects.filter(username=username).count()

        return JsonResponse({'count': count, 'code': '0', 'errmsg': 'OK'})


class RegisterView(View):
    def post(self, request):
        # 步骤
        # 1接受请求
        body_byte = request.body
        # 获取json格式数据 转为字典
        body_dict = json.loads(body_byte)

        # 2获取数据
        username = body_dict.get("username")
        password = body_dict.get("password")
        password2 = body_dict.get("password2")
        mobile = body_dict.get("mobile")
        sms_code = body_dict.get("sms_code")
        allow = body_dict.get("allow")

        # 3验证数据
        # 3.1验证是否为空 有没有传
        # all 里传入列表 如果列表里 任一元素为flase或者空 结果就是false
        if not all([username, password, password2, mobile, sms_code, allow]):
            return JsonResponse({"code": "400", "errmsg": "register fail"})
        # 3.2正则验证
        if not re.match(r'^[a-zA-Z0-9_-]{5,20}$', username):
            return JsonResponse({"code": "400", "errmsg": "register fail"})

        # 短信验证码验证
        # 从redis 获取 短信验证码

        redis_cli = get_redis_connection("code")
        redis_sms_code = redis_cli.get("sms_%s" % mobile)

        # 如果没有验证码 验证码过期
        if redis_sms_code is None:
            return JsonResponse({'code': 400, 'errmsg': "短信验证码过期"})

        if redis_sms_code.decode().lower() != sms_code.lower():
            return JsonResponse({'code': 400, 'errmsg': "短信验证码输入错误"})

        # 4生成用户保存到数据库
        # uesr = User(username=username, password=password, mobile=mobile)
        # user.save();
        try:
            user = User.objects.create_user(username=username, password=password, mobile=mobile)
        # 密码加密   数据保存可能不成功捕获异常
        except Exception as e:
            return JsonResponse({'code': 400, 'errmsg': "用户保存失败"})

        # 保持登录状态
        login(request, user)

        response = JsonResponse({"code": "0", "errmsg": "ok"})
        # 把用户名保存到cookie 方便在首页显示 有效期产品决定
        response.set_cookie('username', user.username, max_age=3600 * 24 * 5)

        # 5返回响应（json数据）
        return response


class LoginView(View):
    def post(self, request):
        # 接收数据
        body = request.body
        data_dict = json.loads(body)
        username = data_dict.get("username")
        password = data_dict.get("password")
        remembered = data_dict.get("remembered")

        # 判断数据 是否为空

        if not all([username, password]):
            return JsonResponse({"code": "400", "errmsg": "参数不全"})
        print("---------", remembered)
        if remembered:
            request.session.set_expiry(None)

        else:
            request.session.set_expiry(0)

        # 根据用户传入的username值，判断手机号还是用户名

        if re.match('1[3-9]\d{9}', username):
            User.USERNAME_FIELD = "mobile"

        else:
            User.USERNAME_FIELD = "username"

        # 验证用户名和密码是否正确

        user = authenticate(username=username, password=password)

        if user is None:
            return JsonResponse({"code": "400", "errmsg": "用户名或者密码错误"})
        # 保持登录状态
        login(request, user)

        response = JsonResponse({"code": "0", "errmsg": "ok"})
        # 把用户名保存到cookie 方便在首页显示 有效期产品决定
        # print("-------",user.username)
        response.set_cookie('username', user.username, max_age=3600 * 24 * 5)

        # 6 返回响应
        return response


class LogoutView(View):
    def delete(self, request):
        logout(request)

        response = JsonResponse({"code": "0", "errmsg": "ok"})

        response.delete_cookie('username')

        return response


class UserInfoView(LoginMixin, View):
    def get(self, request):
        info_data = {
            "username": request.user.username,
            "mobile": request.user.mobile,
            "email": request.user.email,
            "email_active": request.user.email_active
        }

        return JsonResponse({
            'code': 0,
            'errmsg': '个人中心',
            "info_data": info_data
        })


class SaveEmailView(View):
    def put(self, request):
        json_body = request.body
        data_dict = json.loads(json_body)
        email = data_dict.get("email")

        if not email:
            return JsonResponse({"code": "400", "errmsg": "邮箱地址不能为空"})

        if not re.match(r'^[a-z0-9][\w\\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
            return JsonResponse({"code": "400", "errmsg": "邮箱地址格式错误"})

        try:
            request.user.email = email
            request.user.save()
        except Exception as e:
            print(e)

        token = generate_verify_token(request.user.id, request.user.email)

        verify_url = "http://www.meiduo.site:8080/success_verify_email.html?token=%s" % token
        subject = "美多商城邮箱验证"
        recipient_list = [email]
        html_message = "<p>尊敬的用户您好！</p>" \
                       "<p>感谢您使用美多商城。</p>" \
                       "<p>您的邮箱为：%s 。请点击此链接激活您的邮箱：</p>" \
                       "<p><a href='%s'>%s<a></p>" % (email, verify_url, verify_url)
        try:
            send_verify_mail(subject=subject, recipient_list=recipient_list, html_message=html_message)
        except Exception as e:
            print("发送错误", e)

        return JsonResponse({"code": "0", "errmsg": "ok"})


class VerifyEmailView(View):
    def put(self, request):
        # - 1.接收 token
        token = request.GET.get('token')
        if not token:
            return JsonResponse({'code': 400, 'errmsg': 'token缺少'})

        # - 2.解密
        user_data = chack_verify_token(token)
        # - 4.去数据库对比 user_id,email
        try:
            user = User.objects.get(id=user_data.id, email=user_data.email)
        except Exception as e:
            print(e)
            return JsonResponse({'code': 400, 'errmsg': '参数有误!'})

        # - 5.修改激活状态
        try:
            user.email_active = True
            user.save()
            print("激活成功")
            return JsonResponse({'code': 0, 'errmsg': '激活成功!'})
        except Exception as e:
            print("激活失败", e)
            return JsonResponse({'code': 400, 'errmsg': '激活失败!'})




class AddressCreateView(LoginMixin, View):
    def post(self, request):
        body = request.body

        data_dict = json.loads(body)

        receiver = data_dict.get("receiver")
        province_id = data_dict.get("province_id")
        city_id = data_dict.get("city_id")
        district_id = data_dict.get("district_id")
        place = data_dict.get("place")
        mobile = data_dict.get("mobile")
        tel = data_dict.get("tel")
        email = data_dict.get("email")

        if not all([receiver, province_id, city_id, district_id, place, mobile]):
            return JsonResponse({'code': 400, 'errmsg': '缺少参数'})

        # if not re.match(r'^1[3-9]\d{9}$', mobile):
        #     return JsonResponse({'code': 400, 'errmsg': '参数mobile有误'})
        # if tel:
        #     if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
        #         return JsonResponse({'code': 400, 'errmsg': '参数tel有误'})
        # if email:
        #     if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
        #         return JsonResponse({'code': 400, 'errmsg': '参数email有误'})

        user = request.user
        try:
            address = Address.objects.create(
                user=user,
                title=receiver,
                receiver=receiver,
                province_id=province_id,
                city_id=city_id,
                district_id=district_id,
                place=place,
                mobile=mobile,
                tel=tel,
                email=email,
            )
            print("数据保存成功")
        except Exception as e:
            print(e)
            return JsonResponse({'code': 400, 'errmsg': '保存数据失败'})

        address_dict = {
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }

        return JsonResponse({'code': 0, "errmsg": "ok", "address": address_dict})


class AddressView(LoginView, View):
    def get(self, request):
        user = request.user

        addresses = Address.objects.filter(user=user, is_deleted=False)

        addresses_list = []

        for address in addresses:
            addresses_list.append({
                "id": address.id,
                "title": address.title,
                "receiver": address.receiver,
                "province": address.province.name,
                "city": address.city.name,
                "district": address.district.name,
                "place": address.place,
                "mobile": address.mobile,
                "tel": address.tel,
                "email": address.email
            })

        return JsonResponse({'code': 0, 'errmsg': 'ok', "addresses": addresses_list})


class AddressRemoveView(LoginView, View):
    def delete(self, request, address_id):
        print(address_id)
        # 逻辑删除 把is_deleted改为True
        try:
            address = Address.objects.get(id=address_id)

            address.is_deleted = True
            address.save()
        except Exception as e:
            print(e)
            return JsonResponse({'code': 400, 'errmsg': '删除数据失败'})

        return JsonResponse({'code': 0, 'errmsg': '删除成功'})

    def put(self, request, address_id):
        body = request.body

        data_dict = json.loads(body)
        # 1.获取数据
        receiver = data_dict.get("receiver")
        province_id = data_dict.get("province_id")
        city_id = data_dict.get("city_id")
        district_id = data_dict.get("district_id")
        place = data_dict.get("place")
        mobile = data_dict.get("mobile")
        tel = data_dict.get("tel")
        email = data_dict.get("email")

        if not all([receiver, province_id, city_id, district_id, place, mobile]):
            return JsonResponse({'code': 400, 'errmsg': '缺少参数'})

        # if not re.match(r'^1[3-9]\d{9}$', mobile):
        #     return JsonResponse({'code': 400, 'errmsg': '参数mobile有误'})
        # if tel:
        #     if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
        #         return JsonResponse({'code': 400, 'errmsg': '参数tel有误'})
        # if email:
        #     if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
        #         return JsonResponse({'code': 400, 'errmsg': '参数email有误'})
        user = request.user
        # 2.查询数据库
        try:
            Address.objects.filter(id=address_id).update(
                user=user,
                title=receiver,
                receiver=receiver,
                province_id=province_id,
                city_id=city_id,
                district_id=district_id,
                place=place,
                mobile=mobile,
                tel=tel,
                email=email,
            )
            print("数据修改成功")
        except Exception as e:
            print(e)
            return JsonResponse({'code': 400, 'errmsg': '数据修改失败'})
        # 3.返回一个字典
        address = Address.objects.get(id=address_id)
        address_dict = {
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }

        return JsonResponse({'code': 0, "errmsg": "ok", "address": address_dict})


class PasswordView(LoginView,View):
    def put(self, request):
        body = request.body
        data_dict = json.loads(body)
        # 1.获取数据
        old_password = data_dict.get("old_password")
        new_password = data_dict.get("new_password")
        new_password2 = data_dict.get("new_password2")
        # 2.检查密码是否正确
        result = request.user.check_password(old_password)

        if not all([old_password, new_password, new_password2]):
            return JsonResponse({'code': 400, 'errmsg': '参数不全!'})

        if new_password != new_password2:
            return JsonResponse({'code': 400, 'errmsg': '两次密码不一样!'})

        if not result:
            return JsonResponse({'code': 400, 'errmsg': '原始密码不正确'})

        if not re.match(r'^[0-9A-Za-z]{8,20}$', new_password):
            return JsonResponse({'code': 400, 'errmsg': '密码最少8位,最长20位'})

        # 3.从数据库修改密码
        try:
            request.user.set_password(new_password)
            request.user.save()
            print("修改成功")
        except Exception as e:
            print("修改密码失败", e)

        logout(request)
        response = JsonResponse({"code": "0", "errmsg": "ok"})
        # 4.删除cookie
        response.delete_cookie('username')

        return response
